import {ConfigEnv, loadEnv, UserConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import {resolve} from "path";
import vueJsx from '@vitejs/plugin-vue-jsx';
import * as fs from "fs";
import {svgBuilder} from './src/plugins/svg-builder'
import zms from './src/plugins/zms'

export default ({command, mode}: ConfigEnv): UserConfig => {
    const CONFIG = loadEnv(mode, process.cwd());
    /**
     * 运行端口
     */
    const PORT = CONFIG.VITE_APP_PORT ? CONFIG.VITE_APP_PORT : 7001
    /**
     * 代理转发
     */
    const PROXY = {
        '/admin-api': CONFIG.VITE_APP_PROXY
    }

    const ViteCont: { [key: string]: any } = {
        css: {
            preprocessorOptions: {
                scss: {
                    silenceDeprecations: ['legacy-js-api']
                }
            }
        },
        base: CONFIG.VITE_APP_BASE_DIR ? CONFIG.VITE_APP_BASE_DIR : '/',
        plugins: [
            vue(), vueJsx(), svgBuilder('./src/assets/icon-svg/'), zms(command === 'build')
        ],
        resolve: {
            alias: {
                "@": resolve(__dirname, "./src")
            }
        },
        preview: {
            port: PORT,
            proxy: PROXY,
            open: false
        },
        define: {//全局配置
            __APP_DEBUG__: mode === 'development'
        }
    }

    if (mode === 'development') {//本地开发模式
        ViteCont.server = {
            host: CONFIG.VITE_APP_HOST,
            port: PORT,
            proxy: PROXY
        }
    } else if (mode === 'production') {//打包模式
        /**
         * 获取全部应用入口
         */
        let input: { [key: string]: any } = {}
        let flist = fs.readdirSync(__dirname)
        for (let file of flist) {
            if (!file.endsWith(".html")) {
                continue;
            }
            let fname = file.substring(0, file.length - 5)
            input[fname] = resolve(__dirname, file)
        }

        /**
         * 打包配置
         */
        ViteCont.build = {
            sourcemap: false,
            outDir: __dirname + (CONFIG.VITE_APP_BASE_DIR ? `/build${CONFIG.VITE_APP_BASE_DIR}` : '/build'),
            rollupOptions: {input: input}
        }
    }
    return ViteCont
}